package MianCalPak;

import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.SQLException;
import java.util.Properties;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import DB.DBProvider;

/**
 * Servlet implementation class UploadFile
 */
public class UploadFile extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public UploadFile() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request,response);
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) 
	throws ServletException, IOException {
		
		
	try {
		
		String user = (String)request.getSession().getAttribute("username");
		
		if (user == null) {response.sendError(HttpServletResponse.SC_BAD_REQUEST);}
		
		String contentType = request.getContentType();
		
		//saving the file
		if ((contentType != null) && (contentType.indexOf("multipart/form-data") >= 0)) {
			
			DataInputStream in = new DataInputStream(request.getInputStream());
			int formDataLength = request.getContentLength();
			byte dataBytes[] = new byte[formDataLength];
			int byteRead = 0;
			int totalBytesRead = 0;
			
			while (totalBytesRead < formDataLength) {
				byteRead = in.read(dataBytes, totalBytesRead, formDataLength);
				totalBytesRead += byteRead;
			}

			String file = new String(dataBytes);
			
			int lastIndex = contentType.lastIndexOf("=");
			String boundary = contentType.substring(lastIndex + 1,contentType.length());
			
			
			int pos = file.indexOf("filename=\"");

			pos = file.indexOf("\n", pos) + 1;

			pos = file.indexOf("\n", pos) + 1;

			pos = file.indexOf("\n", pos) + 1;


			int boundaryLocation = file.indexOf(boundary, pos) - 4;
			int startPos = ((file.substring(0, pos)).getBytes()).length;
			int endPos = ((file.substring(0, boundaryLocation)).getBytes()).length;
			   
			ByteArrayOutputStream biteArray = new ByteArrayOutputStream();
	        biteArray.write(dataBytes, startPos, (endPos - startPos));
	        biteArray.flush();
	        biteArray.close();
			
			//saving it at the database
			
	        Properties p = new Properties();
	        p.load(getServletContext().getResourceAsStream("/WEB-INF/config"));
	        (new DBProvider(p)).saveXSLTInDB(user, biteArray);
			}
			
			request.getSession().setAttribute("upload","yes");
			response.sendRedirect("index.jsp");

	}
	catch (Exception e) {
			response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
			e.printStackTrace();} 
	}
}